package com.culturalCenter.dataCenter.Utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpConnectionManagerParams;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

import static junit.framework.Assert.assertEquals;

/**
 * @Author zhao
 * @Date 2020/12/22 12:08
 */
@Slf4j
public class RestClientUtil {

    private static HttpClient client = null;

    /**
     * @param host 主机地址
     * @param port 端口名
     * @param uri  要调用的接口
     *
     * @return
     *
     * @throws IOException
     */
    public static String callInterface(String host, int port, String uri) {
        // 准备工作
        client = new HttpClient();
        HttpConnectionManagerParams params = client.getHttpConnectionManager().getParams();
        params.setConnectionTimeout(5000);
        params.setSoTimeout(50000);
        params.setSendBufferSize(8192);
        params.setReceiveBufferSize(8192);
        // 使用HTTP访问
        client.getHostConfiguration().setHost(host, port);
        client.getState().setCredentials(new AuthScope(host, port, "iMC RESTful Web Services"), new UsernamePasswordCredentials("admin", "admin"));
        // 调用接口
        GetMethod get = new GetMethod(uri);
        get.addRequestHeader("accept", "application/xml");

        try {
            assertEquals(HttpStatus.SC_OK, client.executeMethod(get));
            String resultReturn = get.getResponseBodyAsString();
            // 解决返回结果中会中文乱码的现象
            String resultFormat = new String(resultReturn.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
            // 释放这个连接
            get.releaseConnection();
            return resultFormat;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return null;
    }

}
